<?php

namespace app\model;

use app\admin\controller\BaseCategory;
use think\Exception;
use think\facade\Db;
use think\Model;

class DistrictCodesModel extends Model {

    protected $table ="discount_codes";

    protected $pk = 'code';

    private $cacheKey="discount:codes:";

    private $cacheTime=5184000;


    /*
     * 获取total
     * */
    public function getTotal($where=[]){
        return Db::name($this->table)->where($where)->count();
    }


    /*
     * 获取list
     * */
    public function getList($where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =  Db::name($this->table)->field("code")->where($where);


        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
            $obj = $obj->order("code", "ASC");
        }

        $list = $obj->select();

        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $this->getInfo($item['code']);
            }
            return $return;
        }
        return [];
    }



    /*
   * 获取订单状态详情
   * */
    public function getInfo($id){
        $cacheKey = $this->cacheKey.$id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            $info = json_decode($info,true);
        }else{
            $info = Db::name($this->table)->find($id);
            $info['format_min_order_amount'] = round( $info['min_order_amount'] / 100, 2);
            $info['format_discount_amount'] = round( $info['discount_amount'] / 100, 2);
            $redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }

        $info['have_used'] = (new UserUseDiscountCodeLogModel())->getTotal([
            "code"=> $id,
            "is_delete"=>  0,
        ]);

        return $info;
    }


    /*
     * 使用优惠劵
     * */
    public function useDistrictCode($uid,$code){

        $info = $this->getInfo($code);

        if(empty($info)){
            throw new Exception("优惠码错误");
        }

        if(!in_array($info["type"],["percentage"])){
            throw new Exception("暂不支持该类型的优惠码");
        }

        if($info["is_delete"] == 1){
            throw new Exception("优惠码已失效");
        }


        if(strtotime($info["start_time"]) > time()){
            throw new Exception("优惠码未生效");
        }


        if(strtotime($info["end_time"]) < time()){
            throw new Exception("优惠码已过期");
        }

        if(!empty($info["max_uses"]) &&  $info["max_uses"] <= $info["have_used"]){
            throw new Exception("优惠码已用光，下次早点来~");
        }

        //判断是不是一个用户只能使用一次
        if($info["single_use_per_user"] == 1){
            $where=[];
            $where['code'] = $code;
            $where['uid'] = $uid;
            if((new UserUseDiscountCodeLogModel())->getTotal($where) > 0){
                throw new Exception("优惠码已被使用过，不可重复使用~");
            }
        }

        return $info;
    }
}